/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.click.app.webapp.action;

import com.click.app.DateFormatChanger;
import com.click.app.model.LaundryItem;
import com.click.app.model.LaundryRequest;
import com.click.app.model.LaundryRequestItem;
import com.click.app.model.LaundryStorage;
import com.click.app.model.LaundryType;
import com.click.app.model.ModelSize;
import com.click.app.model.PantDesign;
import com.click.app.model.SizeRank;
import com.click.app.model.TradeMark;
import com.click.app.service.GenericManager;
import com.click.app.service.LaundryItemManager;
import com.click.app.service.LaundryRequestItemManager;
import com.click.app.service.LaundryRequestManager;
import com.click.app.service.LaundryStorageManager;
import com.click.app.service.PantDesignManager;
import com.click.app.service.SeamStorageManager;
import com.click.app.webapp.reportObjects.LaundryReceptionTable;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;

import java.util.List;
import java.util.Set;

/**
 * @author Joel Chuca Condo
 */
public class LaundryRequestReceptionAction extends BaseAction {

    private PantDesignManager pantDesignManager;
    private SeamStorageManager seamStorageManager;
    private LaundryRequestItemManager laundryRequestItemManager;
    private LaundryRequestManager laundryRequestManager;
    private GenericManager<TradeMark, Long> tradeMarkManager;
    private GenericManager<LaundryType, Long> laundryTypeManager;
    private GenericManager<SizeRank, Long> sizeRankManager;
    private LaundryItemManager laundryItemManager;
    private LaundryStorageManager laundryStorageManager;
    private LaundryRequest laundryRequest;
    private LaundryRequestItem laundryRequestItem;
    //private SeamStorage seamStorage;
    private PantDesign pantDesign;
    private List laundryRequests;
    private List laundryRequestItems;
    //private List seamStorages;    
    private List laundryTypes;
    private List pantDesigns;
    //private List pantDesignEnables;
    private Set<ModelSize> modelSizes;
    //private Set<ModelSize> modelSizeInputs;
    private List<LaundryItem> laundryItems;
    private String[] quantities;
    private Long id;
    private Long idLaundryRequest;
    private LaundryReceptionTable laundryReceptionTable;
    private String receivedDate;

    public void setLaundryRequestItemManager(LaundryRequestItemManager laundryRequestItemManager) {
        this.laundryRequestItemManager = laundryRequestItemManager;
    }

    public void setLaundryRequestManager(LaundryRequestManager laundryRequestManager) {
        this.laundryRequestManager = laundryRequestManager;
    }

    public void setLaundryTypeManager(GenericManager<LaundryType, Long> laundryTypeManager) {
        this.laundryTypeManager = laundryTypeManager;
    }

    public void setPantDesignManager(PantDesignManager pantDesignManager) {
        this.pantDesignManager = pantDesignManager;
    }

    public void setSeamStorageManager(SeamStorageManager seamStorageManager) {
        this.seamStorageManager = seamStorageManager;
    }

    public void setTrademarkManager(GenericManager<TradeMark, Long> trademarkManager) {
        this.tradeMarkManager = trademarkManager;
    }

    public void setSizeRankManager(GenericManager<SizeRank, Long> sizeRankManager) {
        this.sizeRankManager = sizeRankManager;
    }

    public void setLaundryItemManager(LaundryItemManager laundryItemManager) {
        this.laundryItemManager = laundryItemManager;
    }

    public void setLaundryStorageManager(LaundryStorageManager laundryStorageManager) {
        this.laundryStorageManager = laundryStorageManager;
    }

    public List getLaundryRequestItems() {
        return laundryRequestItems;
    }

    public List getLaundryRequests() {
        return laundryRequests;
    }

    public List getLaundryTypes() {
        return laundryTypes;
    }

    public List<LaundryItem> getLaundryItems() {
        return laundryItems;
    }

    public String[] getQuantities() {
        return quantities;
    }

    public void setQuantities(String[] quantities) {
        this.quantities = quantities;
    }

    public List getPantDesigns() {
        return pantDesigns;
    }

    public Set<ModelSize> getModelSizes() {
        return modelSizes;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getIdLaundryRequest() {
        return idLaundryRequest;
    }

    public void setIdLaundryRequest(Long idLaundryRequest) {
        this.idLaundryRequest = idLaundryRequest;
    }

    public LaundryRequest getLaundryRequest() {
        return laundryRequest;
    }

    public void setLaundryRequest(LaundryRequest laundryRequest) {
        this.laundryRequest = laundryRequest;
    }

    public LaundryRequestItem getLaundryRequestItem() {
        return laundryRequestItem;
    }

    public void setLaundryRequestItem(LaundryRequestItem laundryRequestItem) {
        this.laundryRequestItem = laundryRequestItem;
    }

    public LaundryReceptionTable getLaundryReceptionTable() {
        return laundryReceptionTable;
    }

    public PantDesign getPantDesign() {
        return pantDesign;
    }

    public void setPantDesign(PantDesign pantDesign) {
        this.pantDesign = pantDesign;
    }

    public String getReceivedDate() {
        receivedDate = DateFormatChanger.changeDatetoString(laundryRequest.getEndDate());
        return receivedDate;
    }

    public void setReceivedDate(String receivedDate) {
        this.receivedDate = receivedDate;
        laundryRequest.setEndDate(DateFormatChanger.changeStringtoDate(receivedDate));
        ;
    }

    public String laundryUnReceptionList() {
        laundryRequests = laundryRequestManager.getCurrentPeriodUnReception();
        return SUCCESS;
    }

    public String list() {

        if (idLaundryRequest != null) {
            laundryRequest = laundryRequestManager.get(idLaundryRequest);
            getSession().setAttribute("laundryRequest", laundryRequest);
        } else {
            laundryRequest = ((LaundryRequest) getSession().getAttribute("laundryRequest"));
        }

        if (laundryRequest != null) {
            //update
            laundryRequest = laundryRequestManager.get(laundryRequest.getId());
            modelSizes = sizeRankManager.get(laundryRequest.getSizeRank().getId()).getModelSizes();
            getSession().setAttribute("modelSizes", modelSizes);
            //System.out.println("modelSizes: "+modelSizes);
            //System.out.println("Entroooooo 3");
            laundryReceptionTable = new LaundryReceptionTable(laundryRequest.getLaundryRequestItems(), laundryItemManager, modelSizes);
            if (!(laundryReceptionTable.isCorrect())) {
                errorMessage(getText("Can't show the table "));
                return ERROR;
            }
        } else {
            System.out.println("laundryRequest is null");
            return ERROR;
        }
        return SUCCESS;
    }

    public String edit() {
        System.out.println("........... Start edit (laundryRequestItemAction) ...........");

        laundryRequest = ((LaundryRequest) getSession().getAttribute("laundryRequest"));
        pantDesigns = seamStorageManager.findByModelAndMaterial(laundryRequest.getTradeMark().getId());
        modelSizes = ((Set<ModelSize>) getSession().getAttribute("modelSizes"));
        laundryTypes = laundryTypeManager.getAll();

        if (id != null) {
            laundryRequestItem = laundryRequestItemManager.get(id);
            pantDesign = laundryRequestItem.getLaundryItems().get(0).getPantDesign();

            laundryItems = laundryItemManager.findByOrderSize(laundryRequestItem.getId());
            //System.out.println("luandry itemssss: "+laundryItems);
            quantities = new String[modelSizes.size()];
            for (int i = 0; i < modelSizes.size(); i++) {
                quantities[i] = laundryItems.get(i).getFailQuantity() + "";
            }
        }

        System.out.println("........... End edit ...........");

        return SUCCESS;
    }

    public String save() throws Exception {

        if (cancel != null) {
            return CANCEL;
        }

        if (delete != null) {
            //return delete();
        }

        System.out.println("Quantities dates");
        for (int i = 0; i < quantities.length; i++) {
            System.out.println("quantity: " + quantities[i]);
        }


        Enumeration<String> en = getRequest().getParameterNames();
        while (en.hasMoreElements()) {
            String string = en.nextElement();
            System.out.println("Parameter " + string + ": " + getRequest().getParameter(string));
        }

        boolean isNew = false;
        isNew = (laundryRequestItem.getId() == null);

        String result = verifyInputDatas();
        if (result != null) {
            return result;
        }

        laundryRequestItem.setFailUnitPrice(Float.parseFloat(getRequest().getParameter("laundryRequestItem.failUnitPrice")));
        laundryRequest = (LaundryRequest) getSession().getAttribute("laundryRequest");

        if (!isNew) {
            // -------------  update old datas ------------
            LaundryRequestItem laundryRequestItemOld = laundryRequestItemManager.get(laundryRequestItem.getId());
            laundryItems = new ArrayList<LaundryItem>();
            //List<LaundryItem> laundryItemsOld = laundryRequestItemOld.getLaundryItems();
            for (LaundryItem laundryItem : laundryRequestItemOld.getLaundryItems()) {
                laundryItems.add(laundryItem);
            }

            PantDesign pantDesignOld = laundryRequestItemOld.getLaundryItems().get(0).getPantDesign();

            modelSizes = ((Set<ModelSize>) getSession().getAttribute("modelSizes"));
            laundryItems = laundryItemManager.findByOrderSize(laundryRequestItemOld.getId());
            /*
            for (int i = 0; i < laundryItems.size()-1; i++) {
            for (int j = i+1; j < laundryItems.size(); j++) {
            if(laundryItems.get(i).getPantDesign().getModelSize().getValueSize().compareTo(
            laundryItems.get(j).getPantDesign().getModelSize().getValueSize()) > 0 ){
            LaundryItem laundryItem = laundryItems.get(i);
            laundryItems.set(i, laundryItems.get(j));
            laundryItems.set(j, laundryItem);
            }
            }
            }
             */
            Integer failTotalQuantity = 0;
            for (int i = 0; i < quantities.length; i++) {
                Integer failQuantity = Integer.parseInt(quantities[i]);
                System.out.println("quantity: " + quantities[i]);
                System.out.println(laundryItems.get(i));
                if (failQuantity < laundryItems.get(i).getQuantity()) {
                    laundryItems.get(i).setFailQuantity(failQuantity);
                } else {
                    errorMessage("Error: Fail quantity exceeded the good quantity");
                    return "reload";
                }
                failTotalQuantity += failQuantity;
            }

            laundryRequestItemOld.setLaundryItems(laundryItems);
            laundryRequestItemOld.setFailUnitPrice(laundryRequestItem.getFailUnitPrice());
            laundryRequestItemOld.setFailQuantity(failTotalQuantity);
            laundryRequestItemOld.setFailTotalPrice(laundryRequestItem.getFailUnitPrice() * failTotalQuantity);
            laundryRequestItemOld = laundryRequestItemManager.save(laundryRequestItemOld);
        }

        getSession().setAttribute("laundryRequestItem", null);

        if (isNew) {
            saveMessage(getText("laundryRequestItem.added"));
            return SUCCESS;
        } else {
            saveMessage(getText("laundryRequestItem.updated"));
            return INPUT;
        }
    }

    public String delete() {
        return "delete";
    }

    public String verifyInputDatas() {
        String result = null;

        try {
            for (int i = 0; i < quantities.length; i++) {
                Integer quantity = Integer.parseInt(quantities[i]);
            }

        } catch (Exception e) {
            System.out.println("LaundryRequestItemAction exception: " + e.getMessage());
            saveMessage("Quantity incorrect: the number does't have the format correct");
            result = "reload";
        }



        if (laundryRequestItem.getFailUnitPrice() == null) {
            saveMessage(getText("laundryRequestItemRequired.unitPrice"));
            result = "reload";
        }
        return result;
    }

    public String help() {
        return SUCCESS;
    }

    public String send() {
        if (cancel != null) {
            return CANCEL;
        }

        laundryRequest = ((LaundryRequest) getSession().getAttribute("laundryRequest"));
        laundryRequest = laundryRequestManager.get(laundryRequest.getId());
        laundryRequest.setEndDate(DateFormatChanger.changeStringtoDate(receivedDate));

        if (laundryRequest.getEndDate() != null) {
            laundryRequest = laundryRequestManager.get(laundryRequest.getId());
            List<LaundryRequestItem> laundryRequestItems = laundryRequest.getLaundryRequestItems();

            // update laundry storage
            for (LaundryRequestItem laundryRequestItem : laundryRequestItems) {
                for (LaundryItem laundryItem : laundryRequestItem.getLaundryItems()) {
                    LaundryStorage laundryStorage = laundryStorageManager.findByPantDesignAndTradeMark(laundryItem.getPantDesign().getId(), laundryRequest.getTradeMark().getId());
                    //LaundryStorage laundryStorage= null;
                    if (laundryStorage != null) {
                        laundryStorage.setStock(laundryStorage.getStock() + laundryItem.getQuantity());
                    } else {
                        laundryStorage = new LaundryStorage();
                        laundryStorage.setPantDesign(laundryItem.getPantDesign());
                        laundryStorage.setTradeMark(laundryRequest.getTradeMark());
                        laundryStorage.setStock(laundryItem.getQuantity());
                        laundryStorage.setStockLimit(0);
                    }

                    laundryStorage = laundryStorageManager.save(laundryStorage);
                }
            }
        } else {
            errorMessage("There is not Date");
            return "error";
        }

        laundryRequest = laundryRequestManager.save(laundryRequest);

        getSession().setAttribute("laundryRequest", null);
        getSession().setAttribute("laundryRequestItem", null);
        getSession().setAttribute("pantDesign", null);

        saveMessage("clothes were sended to storage");
        return SUCCESS;
    }
}
